package com.TinyBBS.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.TinyBBS.bean.User;
import com.TinyBBS.model.UserModel;

/**
 * Servlet implementation class SendEmail
 */
public class SendEmail extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uri = "";
		String error = "";
		if (request.getParameter("emailsubmit") == null) {
			uri = "views/retrievePassword.jsp";
		} else {
			HttpSession session = request.getSession();
			String token = request.getParameter("token").trim();
			if (session.getAttribute("emailIdentity") == null) {
				uri = "views/login.jsp";
				error = "Unknown Error:";
			} else {
				User user = new User();
				UserModel userM = new UserModel();
				user = userM.getUserByEmail((String)session.getAttribute("emailIdentity"));
				if (user != null) {
					if (token.equals(user.getToken())) {
						uri = "views/changePassword.jsp";
					} else {
						uri = "views/sendEmail.jsp";
						error = "Token is not corrent";
					}
				}else{
					uri = "views/sendEmail.jsp";
					error = "Unknown Error:";
				}

			}
		}
		request.setAttribute("error", error);
		RequestDispatcher rd = request.getRequestDispatcher(uri);
		rd.forward(request, response);
	}

}
